package com.darker.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.darker.reggie.common.R;
import com.darker.reggie.dto.DishDto;
import com.darker.reggie.entity.Category;
import com.darker.reggie.entity.Dish;
import com.darker.reggie.entity.DishFlavor;
import com.darker.reggie.service.CategoryService;
import com.darker.reggie.service.DishFlavorService;
import com.darker.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Resource
    DishService dishService;

    @Resource
    DishFlavorService dishFlavorService;

    @Resource
    CategoryService categoryService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {

        dishService.saveWithDishFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("添加成功");
    }

    //分页查询 菜品信息
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageinfo = new Page(page, pageSize);
        Page<DishDto> dishdtopage = new Page<>();
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Dish::getName, name);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        dishService.page(pageinfo, queryWrapper);
        //对象拷贝 参数为源对象  拷贝到的对象 不需要拷贝的属性
        BeanUtils.copyProperties(pageinfo, dishdtopage, "records");
        //把Dish中的集合数据赋值给Dish的集合
        List<Dish> dishList = pageinfo.getRecords();
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            //把dish对象的数据赋值给dishDto
            BeanUtils.copyProperties(dish, dishDto);
            //把dish中的categoryID取出来
            Long categoryId = dish.getCategoryId();//分类ID
            //根据id查询出数据赋值给Category对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                //分类菜品的名称取出来
                String categoryName = category.getName();
                //赋值给dishDto对象
                dishDto.setCategoryName(categoryName);
                //最后添加到DishDto集合
                dishDtoList.add(dishDto);
            }

        }
        //最后给分页容器赋值
        dishdtopage.setRecords(dishDtoList);
        return R.success(dishdtopage);
    }

    //根据Id查询菜品 和口味
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable long id) {
        DishDto dishDto = dishService.getWithDishFlavorByid(id);
        return R.success(dishDto);
    }
    //批量删除根据ID
    @DeleteMapping
    public R<String> removebyid(@RequestParam List<Long> ids){
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }
    //批量修改状态
    @PostMapping("/status/{status}")
    public R<String> updateStatus0(@PathVariable int status, @RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.in(Dish::getId,ids);
        lambdaUpdateWrapper.set(Dish::getStatus,status);
        dishService.update(lambdaUpdateWrapper);
        return R.success("状态修改成功");
    }

    //修改菜品
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithDishFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("更新成功");
    }

    //查询分类菜品 的集合
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        LambdaQueryWrapper<Dish> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
//        //查询启售的
//        queryWrapper.eq(Dish::getStatus,1);
//        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return  R.success(list);
//    }
    //查询分类菜品 的集合
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //从redis中获取数据
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //如果数据存在直接返回
        if (dishDtoList != null) {
            return R.success(dishDtoList);
        }

        //数据库不存在 再从数据从查
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询启售的
        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.like(dish.getName() != null, Dish::getName, dish.getName());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = new ArrayList<>();
        for (Dish dish1 : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish1, dishDto);
            //根据id查询出数据赋值给Category对象
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper();
            queryWrapper1.eq(dish1.getId() != null, DishFlavor::getDishId, dish1.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        //把数据存入redis 60分钟失效
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);


        return R.success(dishDtoList);
    }
}
